package com.woniu.car.common;

import com.aliyun.oss.ServiceException;
import com.woniu.car.constant.CommonConstant;
import com.woniu.car.exception.AccountException;
import com.woniu.car.exception.ParamException;
import com.woniu.car.exception.ServiceSException;
import com.woniu.car.exception.StatisticsException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindException;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.ArrayList;
import java.util.List;

@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler {
//    @ExceptionHandler(Exception.class)
//    public ResponseEntity exceptionHandler(Exception e){
//        log.info("Exception:" + e.getMessage());
//        return new ResponseEntity().setMsg(e.getMessage()).setCode(CommonConstant.EXCEP);
//    }

    @ExceptionHandler(BindException.class)
    public ResponseEntity bindExceptionHandler(BindException e){

        BindingResult bindingResult = e.getBindingResult();
        List<ObjectError> allErrors = bindingResult.getAllErrors();

        List<String> list = new ArrayList<>();

        for (ObjectError error : allErrors) {
            String defaultMessage = error.getDefaultMessage();
            list.add(defaultMessage);
        }

        log.info("ParamException:" + e.getMessage());
        return new ResponseEntity().setCode(CommonConstant.PARAM).setObject(list);
    }

    @ExceptionHandler(ParamException.class)
    public ResponseEntity paramExceptionHandler(ParamException e){
        log.info("ParamException:" + e.getMessage());
        return new ResponseEntity().setMsg(e.getMessage()).setCode(CommonConstant.PARAM);
    }

    @ExceptionHandler(StatisticsException.class)
    public ResponseEntity StatisticsExceptionHandler(Exception e){
        log.info("StatisticsException:" + e.getMessage());
        return new ResponseEntity().setMsg(e.getMessage()).setCode(CommonConstant.PARAM);
    }

    @ExceptionHandler(ServiceSException.class)
    public ResponseEntity ServiceExceptionHandler(ServiceSException e){
        log.info("ServiceException:" + e.getMessage());
        return new ResponseEntity().setMsg(e.getMessage()).setCode(CommonConstant.PARAM);
    }

    @ExceptionHandler(AccountException.class)
    public ResponseEntity accountExceptionHandler(AccountException e){
        log.info("AccountException:" + e.getMessage());
        return new ResponseEntity().setMsg(e.getMessage()).setCode(CommonConstant.PARAM);
    }
//    @ExceptionHandler(NullPointerException.class)
//    public ResponseEntity aullPointerExceptionHandler(NullPointerException e){
//        log.info("NullPointerException:" + e.getMessage());
//        return new ResponseEntity().setMsg(e.getMessage()).setCode(CommonConstant.PARAM);
//    }

}
